package Dao;

import domain.Student;
import utils.StuUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DaoImpl  implements  IDao{
    @Override
    public List<Student> list(Student student) throws SQLException {
        Connection conn = StuUtils.getConnection();

        String sql = "select * from student where 1=1 ";
        if (student.getName() != null && !student.getName().isEmpty()) {
            sql += " and name like ?";
        }

        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        int i = 1;
        if (student.getName() != null && !student.getName().isEmpty()) {
            preparedStatement.setString(i++, "%" + student.getName() + "%");
        }

        // 执行sql
        ResultSet rs = preparedStatement.executeQuery();
        List<Student> list = new ArrayList<Student>();
        while (rs.next()) {
            list.add(new Student(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getString("sex"),
                    rs.getInt("age"),
                    rs.getString("phone")
            ));
        }
        preparedStatement.close();
        conn.close();
        return list;
    }
    @Override
    public void addStudent(Student student) throws SQLException {
        Connection conn = StuUtils.getConnection();
        String sql = "INSERT INTO student (name, age, sex, phone) VALUES (?, ?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, student.getName());
        pstmt.setInt(2, student.getAge());
        pstmt.setString(3, student.getSex());
        pstmt.setString(4, student.getPhone());
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }

    @Override
    public void updateStudent(Student student) throws SQLException {
        Connection conn = StuUtils.getConnection();
        String sql = "UPDATE student SET name=?, age=?, sex=?, phone=? WHERE id=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, student.getName());
        pstmt.setInt(2, student.getAge());
        pstmt.setString(3, student.getSex());
        pstmt.setString(4, student.getPhone());
        pstmt.setInt(5, student.getId());
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }

    @Override
    public void deleteStudent(int id) throws SQLException {
        Connection conn = StuUtils.getConnection();
        String sql = "DELETE FROM student WHERE id=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, id);
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }

}
